#include "windowpos.h"
#include "ui_windowpos.h"

#include <QMenu>
#include <screenutil.h>

struct MenuAction {
    QString action;
    ScreenCallback callback;
};

WindowPos::WindowPos(QWidget *parent)
    : QWidget{parent}
    , ui(new Ui::WindowPos)
{
    ui->setupUi(this);
    setContextMenuPolicy(Qt::CustomContextMenu);

    QList<MenuAction> *actions = new QList<MenuAction>{
        {"TopLeft", ScreenUtil::moveScreenTopLeft},
        {"TopCenter", ScreenUtil::moveScreenTopCenter},
        {"", nullptr},
        {"Center", ScreenUtil::moveScreenCenter},
        {"CenterMiddleUp", ScreenUtil::moveScreenCenterMiddleUp},
        {"", nullptr},
        {"BottomLeft", ScreenUtil::moveScreenBottomLeft},
        {"BottomRight", ScreenUtil::moveScreenBottomRight},
    };

    if (parent) {
        // 非独立窗口，触发 actionsPos 操作，期望移动父窗口
        connect(this, &QWidget::customContextMenuRequested, this, [this, actions](){
            QMenu menu;
            foreach (MenuAction act, *actions) {
                if (act.action.isEmpty()) {
                    menu.addSeparator();
                    continue;
                }
                menu.addAction(act.action, [this, act](){emit actionPos(act.action, act.callback);});
            }
            menu.exec(QCursor::pos());
        });
    } else {
        // 独立窗口，直接移动自身
        connect(this, &QWidget::customContextMenuRequested, this, [this, actions](){
            QMenu menu;
            foreach (MenuAction act, *actions) {
                if (act.action.isEmpty()) {
                    menu.addSeparator();
                    continue;
                }
                menu.addAction(act.action, [this, act](){act.callback(*this, windowHandle()->screen());});
            }
            menu.exec(QCursor::pos());
        });
    }

    setFixedSize(600, 400);
}
